//
//  ReportDateCell.swift
//  ANOA
//
//  Created by zwb on 2016/11/16.
//  Copyright © 2025 aowang. All rights reserved.
//

import UIKit
import ObjectMapper
class ReportSelectCell: UITableViewCell,DateWidgetable {
    
    @IBOutlet weak var titleLabel: UILabel!
    lazy var dateTextfiled: UIButton = {
       let v = UIButton()
        v.titleLabel?.numberOfLines = 2
//        v.titleLabel?.textAlignment = .right 这句无效哦
        v.setTitleColor(UIColor(kshex: "FF7E00"), for: .normal)
         v.contentHorizontalAlignment = .right
        return v
    }()
    
    fileprivate var itemIdNm = [(String,String)]()
  
    weak var controller:UIViewController?
    
    weak var delegate:ReportViewController?
    
    var reportCellItemSelAct: ((String) -> Void)?
    var pickerData = [String]() {
        didSet {
            
            // 截取选项 "s_amount_z#?销量;s_money#?销售金额;s_agio#?折扣;s_month#?月份;s_month"
            // ["销量", "销售金额", "折扣", "月份"]"
           let itemNames = pickerData.compactMap { (a) -> String? in
                if a.contains("?") {
                    return String(a[a.index(a.firstIndex(of: "?")!, offsetBy: 1)...])
                } else {
                    return nil
                }
            }
            
            // ["s_amount_z", "s_money", "s_agio", "s_month"]"
         let itemIDs = self.pickerData.compactMap { (a) -> String? in
                if a.contains("?") {
                    return String(a[..<a.index(a.firstIndex(of: "?")!, offsetBy: -1)])
                } else {
                    return nil
                }
            }
            guard itemNames.count == itemIDs.count else {
                KSToast("数据源异常")
                return
            }
            itemIdNm.removeAll()
            for i in 0..<itemIDs.count {
                itemIdNm.append((itemIDs[i],itemNames[i]))
            }
        }
    }
    
    var reportParameter: ReportDetail? {
        didSet {
            
            guard let type = reportParameter?.typeCs else {
                return
            }
            var titleShow = reportParameter?.titleCs
            if containsChineseCharacter(reportParameter!.titleNm.unwrap) {
                titleShow = reportParameter?.titleNm
            }
            titleLabel.text = titleShow
            
            switch type {
            case "1": // 单选
                
                let btn = UIButton(frame: self.frame)
                btn.backgroundColor = UIColor.clear
                btn.addTarget(self, action: #selector(clickSingleBtn), for: .touchUpInside)
                addSubview(btn)

                if reportParameter?.ifSession == "1" {
                    // ifSession 查公司  用户基本信息等类型
                    dateTextfiled.addTouchUpInSideAction { _ in
                        if self.reportParameter!.defaultVal == "staff_id" {
                           
                            var allArr = [nameAndModel<String>]()
                            let arrr = [USERINFO.staffNm.unwrap]
                            for i in 0..<arrr.count {
                                let one_x = nameAndModel(shows: [arrr[i]], model: arrr[i])
                                allArr.append(one_x)
                            }
                            
                            let cle:(nameAndModel<String>)->() = { one in
                                self.dateTextfiled.setTitle(one.model, for: .normal)

                             
                                self.addChar(USERINFO.staffId.unwrap)
                             }
                             let vc = KSSingleSelectUtil.initWithNav(title: "选择", allArr: allArr, backClosure: cle)
                            let topViewController = RouterUtils.currentTopViewController()
                            topViewController!.present_FullScreen(to: vc)
                            
                        } else {
                            KSOrgSelectUtil.initWithNav(type: .single, sessionK: self.reportParameter?.sessionKey ?? "",backClosure: { nodes in
                                self.dateTextfiled.setTitle(nodes.first!.name, for: .normal)
             
                                
                                if self.reportParameter!.defaultVal == "org_code"  { // 自己所在的公司
                                    self.addChar(nodes.first!.id.unwrap)
                                } else if self.reportParameter!.defaultVal == "org_name" { // 自己所在的公司
                                    self.addChar(nodes.first!.name.unwrap)
                                }
                                 
                                
                            }){ vc in
                                let topViewController = RouterUtils.currentTopViewController()
                                topViewController!.present_FullScreen(to: vc)
                            }
                        }
                        
                    }
                    
                    if reportParameter!.defaultVal == "org_code"  { // 自己所在的公司
                        dateTextfiled.setTitle(USERINFO.cUnitnameHs, for: .normal)
                            if let unitId = USERINFO.cUnitnameIdHs {
                                self.addChar(unitId)
                            }
                  } else if reportParameter!.defaultVal == "org_name" { // 自己所在的公司
                      dateTextfiled.setTitle(USERINFO.cUnitnameHs, for: .normal)
                        if let unitId = USERINFO.cUnitnameHs {
                            self.addChar(unitId)
                        }
                    }  else   if reportParameter!.defaultVal == "managred_unit" ||
                                    reportParameter!.defaultVal == "managred_unit_nm" ||
                                         reportParameter?.defaultVal == "managred_sp_unit" ||
                                        reportParameter?.defaultVal == "managred_my_unit" ||
                                        reportParameter?.defaultVal == "managred_sl_unit" ||
                                        reportParameter?.defaultVal == "managred_yz_unit" { // 管理的公司 多个
                        dateTextfiled.setTitle(USERINFO.managredUnitNm, for: .normal)
                    
                           if let unitId = USERINFO.managredUnit {
                            self.addChar(unitId)
                        }
                    }
                      else    if reportParameter!.defaultVal == "staff_id" {
                          dateTextfiled.setTitle(USERINFO.staffNm, for: .normal)

                      
                           if let staffid = USERINFO.staffId {
                            self.addChar(staffid)
                        }
                    } else {
                        dateTextfiled.setTitle("[未识别配置]", for: .normal)
 

                    }
                   
                    
                    
                } else {
                    
                    let remark = reportParameter?.sRemarks ?? ""
                     guard remark != "" else {
                        return
                    }
                    
                    pickerData = remark.components(separatedBy: ";")
               
                    dateTextfiled.setTitle(itemIdNm.first?.1, for: .normal)

                    
                    dateTextfiled.addTouchUpInSideAction { _ in
                        var allArr = [nameAndModel<(String,String)>]()
                        for i in 0..<self.itemIdNm.count {
                            let one_a = nameAndModel(shows: [self.itemIdNm[i].1], model: self.itemIdNm[i])
                            allArr.append(one_a)
                        }
                        let cle:(nameAndModel<(String,String)>)->() = { one in
                            
                            self.dateTextfiled.setTitle(one.model.1, for: .normal)
                                 
                               self.addChar(one.model.0)
                            
                        }
                         let vc = KSSingleSelectUtil.initWithNav(title: "选择", allArr: allArr, backClosure: cle)
                        let topViewController = RouterUtils.currentTopViewController()
                        topViewController!.present_FullScreen(to: vc)
                    }
              
                    
                    self.addChar(self.itemIdNm.first?.0)
                }
                
            case "4": // 月份选择 1 当月， 2 上个月， 3 前N个月
                
                if reportParameter?.defaultVal == "1" {
                    dateTextfiled.setTitle(Date.currentMonth, for: .normal)

                    
                } else if reportParameter?.defaultVal == "2" {
                    dateTextfiled.setTitle(getPrevYearAndMonth(1), for: .normal)

                    
                } else if reportParameter?.defaultVal == "3" {
                    if let n = reportParameter?.sRemarks {
                        dateTextfiled.setTitle(getPrevYearAndMonth(Int(n) ?? 1), for: .normal)

                       
                    } else {
                        dateTextfiled.setTitle(getPrevYearAndMonth(1), for: .normal)
 
                    }
                }
                
                dateTextfiled.addTouchUpInSideAction { _ in
                    let view = SelectMonthView()
                    view.fetchData = { month in
                        self.dateTextfiled.setTitle(month, for: .normal)

                     
                        self.addChar(month)
                    }
                    view.show()
                }
                
            case "5": // 日期选择 1 当天， 2 当月第一天， 3 前n天
                
                if reportParameter?.defaultVal == "1" {
                    dateTextfiled.setTitle(Date.today, for: .normal)

               
                } else if reportParameter?.defaultVal == "2" {
                    dateTextfiled.setTitle(Date.firstDateOfMonth, for: .normal)

                   
                } else if reportParameter?.defaultVal == "3" {
                    if let n = reportParameter?.sRemarks {
                        dateTextfiled.setTitle(getPrevDay(Double(n) ?? 1.0), for: .normal)
 
                    } else {
                        dateTextfiled.setTitle(getPrevDay(1.0), for: .normal)
 
                    }
                    
                }
                dateTextfiled.addTouchUpInSideAction { _ in
                    if let vc = self.controller {
                       
                        self.showDateSelect(vc) { str in
                            self.dateTextfiled.setTitle(str, for: .normal)
                      
                            self.addChar(str)
                            KSLog("报表——开始时间\(str)")
                        }
                    }

                }
            case "6": // lov
                dateTextfiled.addTouchUpInSideAction { _ in
                    self.clickLovBtn()
                }
            
                case "7":
                    // 选择年份
                    if reportParameter?.defaultVal == "1" {
                        dateTextfiled.setTitle(Date.currentYear, for: .normal)
                    }
                    dateTextfiled.addTouchUpInSideAction { _ in
                        let view = SelectYearView()
                        view.fetchData = { year in
                            self.dateTextfiled.setTitle(year, for: .normal)
                            self.addChar(year)
                        }
                        view.show()
                    }
                    break
            
            default: return
            }
        }
    }
    //  lov 查询方法
    @objc func clickLovBtn() {
        // 组装需要关联的参数，并校验不为空
        let vali = Validation()
        
        var dic:[String:String] = [:]
        if !self.reportParameter!.rCol.unwrap.isEmpty {
            let arr = self.reportParameter!.rCol.unwrap.components(separatedBy: ",")
            
            for item in arr {
                let aimP = self.delegate!.allParamItems.filter { item == $0.titleNm }
                if aimP.count > 0 {
                    if aimP.first!.ifShow == "1" {
                        dic.updateValue(self.delegate!.parameterDic[aimP.first!.titleNm.unwrap] ?? "", forKey: aimP.first!.titleNm.unwrap)
                        vali.required(value: self.delegate!.parameterDic[aimP.first!.titleNm.unwrap], msg: "\(aimP.first!.titleCs.unwrap)不为空")
                        
                    } else {
                        if aimP.first!.ifSession == "1" && aimP.first!.sessionKey == "staff_id" {
                            dic.updateValue(USERINFO.staffId.unwrap, forKey: aimP.first!.titleNm.unwrap)
                         }
                        if aimP.first!.ifSession == "1" && aimP.first!.sessionKey == "dept_id" {
                            dic.updateValue(USERINFO.deptId.unwrap, forKey: aimP.first!.titleNm.unwrap)
                         }
                    }
                }
            }
        }
         guard vali.validate() else { return }
        
 // sql 配置限制接收 c_code  c_name
        KSNetwork.shared.doRequest(API.global(.queryReportInfoLovById(id_key: reportParameter!.idKey.unwrap,other:dic))) { (data:BaseResult<LovParamModel>) in
            if data.flag == TRUE {
                if let infos = data.infos {
                    if self.reportParameter!.sDx == "1" { // 多选
                        var allArr = [(LovParamModel,Bool)]()
                        for i in 0..<infos.count {
                             allArr.append((infos[i],false))
                        }
                        let cle:([Any])->() = { arr in
                            self.dateTextfiled.setTitle(arr.compactMap{ ($0 as! LovParamModel).c_name }.joined(separator: ","), for: .normal)

                          
                            self.addChar(arr.compactMap{ ($0 as! LovParamModel).c_code }.joined(separator: ","))
                            
                        }
                        let showC:((GlobalTableViewCell, Any) -> ()) = { cell, model in
                            var contArr:[(String,String?)]!
                            contArr = [
                                       ("","\((model as! LovParamModel).c_name.unwrap)")
                                    ]
                           cell.setDataSource(contentArr: contArr)
                        }
                        let filterC:((Any, String) -> (Bool)) = { model, keyword -> Bool in
                            return (model as! LovParamModel).c_name.unwrap.contains(keyword)
                        }
                         let vc = KSMultiSelectUtil.initWithNav(title: "多选选择", allArr: allArr, backClosure: cle,kSShowCell: showC , filterClosure: filterC)
                        let topViewController = RouterUtils.currentTopViewController()
                        topViewController!.present_FullScreen(to: vc)
                        
                    } else {  // 单选
                        var allArr = [nameAndModel<LovParamModel>]()
                        for i in 0..<infos.count {
                            let one_a = nameAndModel(shows: [infos[i].c_name.unwrap], model: infos[i])
                            allArr.append(one_a)
                        }
                        let cle:(nameAndModel<LovParamModel>)->() = { one in
                            self.dateTextfiled.setTitle(one.model.c_name, for: .normal)
                           
                            self.addChar(one.model.c_code.unwrap)
                            
                        }
                         let vc = KSSingleSelectUtil.initWithNav(title: "单选选择", allArr: allArr, backClosure: cle)
                        let topViewController = RouterUtils.currentTopViewController()
                        topViewController!.present_FullScreen(to: vc)
                        
                    }
                    
                    
              
                    
                }
            } else {
                KSToast(data.errorCombine.unwrap)
            }
        }
    }
    
   
    @objc func clickSingleBtn() {
        
        
        
        var allArr = [nameAndModel<(String,String)>]()
        for i in 0..<itemIdNm.count {
            let one_x = nameAndModel(shows: [itemIdNm[i].1], model: itemIdNm[i])
            allArr.append(one_x)
        }
        
        let cle:(nameAndModel<(String,String)>)->() = { one in
            self.dateTextfiled.setTitle(one.model.0, for: .normal)

          
            self.addChar(one.model.1)
            
        }
        
        let vc = KSSingleSelectUtil.initWithNav(title: "选择", allArr: allArr, backClosure: cle)
        let topViewController = RouterUtils.currentTopViewController()
        topViewController!.present_FullScreen(to: vc)
        
        
        
    }
    
    // 添加前置符和后置符  然后返还给控制器
    fileprivate func addChar(_ para: String?) {
        if let selectAction = self.reportCellItemSelAct {
            let postChar = self.reportParameter?.sPostChar ?? ""
            let sPrefixChar = self.reportParameter?.sPrefixChar ?? ""
            selectAction(sPrefixChar + para.unwrap + postChar)
        }
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        self.contentView.addSubview(dateTextfiled)
        dateTextfiled.snp.makeConstraints { make in
            make.left.equalTo(titleLabel.snp.right)
            make.top.bottom.equalToSuperview()
            make.right.equalToSuperview().offset(-35)
        }
    }
    
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        
        // Configure the view for the selected state
    }
    
}

 

 

class LovParamModel: Mappable {
    
    var c_code: String?
    var c_name: String?
    
    
    
    required init?(map: Map) {
        
    }
    // Mappable
    func mapping(map: Map) {
        
        c_code <- (map["c_code"],StringTransform())
        c_name <- map["c_name"]
        
    }
    
}
